package com.yunsuo.service;

import com.alibaba.fastjson.JSON;
import com.yunsuo.bean.FingerPrintRaspberry;
import com.yunsuo.bean.HttpConnection;
import com.yunsuo.bean.HttpConnectionAddFinger;
import com.yunsuo.bean.HttpConnectionFinal;
import sun.tools.java.Environment;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

public class AddFingerPrint {
    //添加指纹

    //    1.添加指纹
//
//    getImage.py  获取指纹
//    ganchar_1.py 获取成功后调用，生成特征文件
//
//    getImage.py 再次获取指纹
//    ganchar_2.py 获取成功后调用，生成特征文件
//
//    regmodel.py 合并两个指纹的特征文件，生成指纹模版文件
//
//    ValidTemple.py 获得当前指纹数量
//
//
//    storeChar.py 将指纹模版文件保存到指纹库指定位置（这里需要有指纹数量变量传给py文件，并把变量写到请求指令当中），并把位置信息发送给树莓派，保存到数据库
//    upload.py 上传指纹模版文件到树莓派
    public static void add(String u_id, int l_id, String fName) {
        Process ps = null;
        try {
            Process ps1 = null;
            //System.out.println("use speek.py");
            ////System.out.println("open.py");
            try {
                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //System.out.println("anxiazhiwen------------->>>>>>>>>>>>>>>>>>");
            //Thread.sleep(3000);
            ps = Runtime.getRuntime().exec("python3 " + "/home/pi/Door/fingerSplit/getImage.py");
            int status1 = ps.waitFor();//返回0为成功
            //System.out.println(status1);

            //System.out.println("wanchengzhiwenan-------->>>>>>>>>>>>>>>>>>");
            ps1 = null;
            //System.out.println("use speek.py");
            ////System.out.println("open.py");
            try {
                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //Thread.sleep(3000);
            ps = Runtime.getRuntime().exec("python3 " + "/home/pi/Door/fingerSplit/ganchar_1.py");
            status1 = ps.waitFor();//返回0为成功
            //System.out.println(status1);


            //System.out.println("anxiazhiwen------------->>>>>>>>>>>>>>>>>>");
            ps1 = null;
            //System.out.println("use speek.py");
            ////System.out.println("open.py");
            try {
                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //Thread.sleep(3000);
            ps = Runtime.getRuntime().exec("python3 " + "/home/pi/Door/fingerSplit/getImage.py");
            status1 = ps.waitFor();//返回0为成功
            //System.out.println(status1);
            //System.out.println("wanchengzhiwenan-------->>>>>>>>>>>>>>>>>>");
            ps1 = null;
            //System.out.println("use speek.py");
            ////System.out.println("open.py");
            try {
                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //Thread.sleep(3000);
            ps = Runtime.getRuntime().exec("python3 " + "/home/pi/Door/fingerSplit/ganchar_2.py");
            status1 = ps.waitFor();//返回0为成功
            //System.out.println(status1);

            ps = Runtime.getRuntime().exec("python3 " + "/home/pi/Door/fingerSplit/regmodel.py");
            status1 = ps.waitFor();//返回0为成功
            //System.out.println(status1);
            ps1 = null;
            //System.out.println("use speek.py");
            ////System.out.println("open.py");
            try {
                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
            } catch (IOException e) {
                e.printStackTrace();
            }
            Thread.sleep(500);
            ps1 = null;
            //System.out.println("use speek.py");
            ////System.out.println("open.py");
            try {
                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
            } catch (IOException e) {
                e.printStackTrace();
            }

            //创建指纹目录
            String path = "/home/pi/finger/" + l_id + "/" + u_id;
            //System.out.println("path=" + path);
            File file = new File(path);
            Boolean bbc = file.mkdirs();// ture

            String position1 = "";

            try {
                String[] args = new String[]{"python3", "/home/pi/Door/fingerSplit/ValidTemple.py", path};
                ps = Runtime.getRuntime().exec(args);

                //Process process = Runtime.getRuntime().exec("python3 ValidTemple.py",path);
//            process.waitFor();
                InputStreamReader ir = new InputStreamReader(ps.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);
                String str = "";
                while ((str = input.readLine()) != null) {
                    //System.out.println("result==" + str);
                    position1 = str;
                }
//            result = input.readLine();
//            //System.out.println("result=="+result);
                status1 = ps.waitFor();//返回0为成功
                //System.out.println(status1);
                input.close();
                ir.close();
//            process.waitFor();
            } catch (IOException e) {
                //logger.error("调用python脚本并读取结果时出错：" + e.getMessage());
                e.printStackTrace();
            }
//            //调用ValidTemple.py 获取当前的指纹数量,并保存到指纹模块
//            ps = Runtime.getRuntime().exec("python3 "+ "ValidTemple.py");
//            status1 = ps.waitFor();//返回0为成功
//            //System.out.println(status1);

            //生成指纹完整路径
            //System.out.println("position1=" + position1);
            String fingerContent = path + "/" + position1;
            //System.out.println("fingerContent=" + fingerContent);
            //生成uuid
            String uuid = "";
            uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //System.out.println(uuid);


            //把指纹信息保存到数据库
            //。。。。。。。。。。。。。。。。。。。
            // 1.加载数据访问驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.连接到数据"库"上去
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/raspberry?characterEncoding=UTF-8", "root", "123456");
            //3.构建SQL命令
            Statement state = conn.createStatement();
            String s = "insert into fingerprint_raspberry" +
                    "(f_uuid,f_name,f_lock_id,f_user_id,f_content_path,f_delete,f_is_modify) " +
                    "VALUES('" + uuid + "','" + uuid + "'," + l_id + "," + u_id + ",'" + fingerContent + "'," + 0 + "," + 0 + ")";
            //System.out.println("sql mingling:" + s);
            state.executeUpdate(s);
            conn.close();//关闭连接

            FingerPrintRaspberry fpr = new FingerPrintRaspberry();
            fpr.setfContentPath(fingerContent);
            fpr.setfLockId(l_id);
            fpr.setfName(fName);
            fpr.setfUserId(Integer.valueOf(u_id));
            fpr.setfDelete(0);
            fpr.setfIsModify(0);
            fpr.setfUuid(uuid);
            fpr.setfId(null);

            //指纹信息生成成功，发送给服务器
            String jsonString = JSON.toJSONString(fpr);
            //System.out.println("addFinger:" + jsonString);
            final String info = "info=" + jsonString;
            HttpConnectionFinal httpConnection = new HttpConnectionFinal();
            String result = httpConnection.connection("/raspberry/addFinger", info);
            //System.out.println("serverback=" + result);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void addFingerFile(String path, String fileName,int l_id,int userID) {
        //System.out.println("---------------------------");
        //System.out.println("addFingerFile");
        //System.out.println("path=" + path);
        //System.out.println("fileName=" + fileName);
        String url = "http://192.168.43.203:8081/imagesA/finger/" + path + fileName;
        //System.out.println("url=" + url);
        //pathRaspberry表示从服务器获得的指纹文件要存放在树莓派的本地目录
        String pathRaspberry = "/home/pi/finger/" + path + fileName;
        //System.out.println("pathRaspberry=" + pathRaspberry);
        //获得文件路径
        File file1=new File(pathRaspberry);
        //System.out.println("----------------00000000000000000");
        //System.out.println(file1.getParent());
        ////System.out.println("fileName---->"+filePath);/Users/leo/finger/2
        //创建不同的文件夹目录
        File file = new File(file1.getParent());
        //判断文件夹是否存在
        if (!file.exists()) {
            //如果文件夹不存在，则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            // 建立链接
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10*1000);
            conn.setConnectTimeout(10*1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾

            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(pathRaspberry);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();


            //指纹信息生成成功，存到本地数据库中，然后发送到服务器存储
            String uuid = "";
            uuid = UUID.randomUUID().toString().replaceAll("-", "");

            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.连接到数据"库"上去
            Connection conn1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/raspberry?characterEncoding=UTF-8", "root", "123456");
            //3.构建SQL命令
            Statement state = conn1.createStatement();
            String s = "insert into fingerprint_raspberry" +
                    "(f_uuid,f_name,f_lock_id,f_user_id,f_content_path,f_delete,f_is_modify) " +
                    "VALUES('" + uuid + "','" + uuid + "'," + l_id + "," + userID + ",'" + "/home/pi/finger/"+path+"00" + "'," + 0 + "," + 0 + ")";
            //System.out.println("sql命令:" + s);
            state.executeUpdate(s);
            conn1.close();//关闭连接

//            //指纹信息生成成功，发送给服务器,因为在服务器已经完成了指纹信息在数据库的存储，所有不需要树莓派再发送一次
//
//            FingerPrintRaspberry fpr = new FingerPrintRaspberry();
//            fpr.setfContentPath("/home/pi/finger/"+path+"01");
//            fpr.setfLockId(l_id);
//            fpr.setfName(fileName);
//            fpr.setfUserId(0);
//            fpr.setfDelete(0);
//            fpr.setfIsModify(0);
//            fpr.setfUuid(uuid);
//            fpr.setfId(null);
//            String jsonString = JSON.toJSONString(fpr);
//            //System.out.println("addFinger:" + jsonString);
//            final String info = "info=" + jsonString;
//            HttpConnectionFinal httpConnection = new HttpConnectionFinal();
//            String result = httpConnection.connection("/raspberry/addFinger", info);
//            //System.out.println("服务器添加指纹信息的返回值=" + result);
            //System.out.println("downFingerFile");
            downFinger(pathRaspberry);
            //System.out.println("storeChar");
            storeChar();

            //把获得的指纹信息，下载到指纹模块中。


        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println("抛出异常！！");
        }
    }


    public static void downFinger(String path){
        Process ps = null;
        String[] args = new String[]{"python3", "/home/pi/Door/fingerSplit/downChar.py", path};
        try {
            ps = Runtime.getRuntime().exec(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Process process = Runtime.getRuntime().exec("python3 ValidTemple.py",path);
//            process.waitFor();
        int status1 = 0;//返回0为成功
        try {
            status1 = ps.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void storeChar(){
        Process ps = null;
        //String[] args = new String[] { "python3","/home/pi/Door/fingerSplit/ValidTemple.py",path};
        try {
            ps = Runtime.getRuntime().exec("python3 "+ "/home/pi/Door/fingerSplit/storeChar.py");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Process process = Runtime.getRuntime().exec("python3 ValidTemple.py",path);
//            process.waitFor();
        int status1 = 0;//返回0为成功
        try {
            status1 = ps.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
